package com.speed.params;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.*;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

/**
 * 初始化加载配置文件类
 * 
 * @date 2016年8月1日 上午10:47:53
 * @author wangjwm
 *
 */
public class ParamsEngine implements ServletContextListener {

	// Properties配置文件路径

	public static final String configPath = "properties/info.properties";
	public static Properties infoConfig = new Properties();

	public static Properties getInfoConfig() {
		return infoConfig;
	}

	public static void setInfoConfig(Properties infoConfig) {
		ParamsEngine.infoConfig = infoConfig;
	}

	/**
	 * 保存变量
	 *
	 * @param params
     */
	public static void saveProperty(Map<String, String> params) {
		// 更新缓存
		Iterator<String> keysIterator = params.keySet().iterator();
 		while(keysIterator.hasNext()){
 		    String key = keysIterator.next();
            ParamsEngine.getInfoConfig().setProperty(key,params.get(key));
        }
		// 改变prop文件
		URL url = ParamsEngine.class.getClassLoader().getResource(ParamsEngine.configPath);
		String file = url.getFile();
		Properties prop = ParamsEngine.getInfoConfig();
		try {
			FileOutputStream fos = new FileOutputStream(file);
			prop.store(fos, null);
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void contextDestroyed(ServletContextEvent arg0) {
	}

	public void contextInitialized(ServletContextEvent arg0) {
		// 加载固定参数地址
		ClassLoader classLoader = ParamsEngine.class.getClassLoader();
		InputStream in = classLoader.getResourceAsStream(ParamsEngine.configPath);
		Properties prop = new Properties();
		try {
			prop.load(in);
			ParamsEngine.setInfoConfig(prop);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
